/**
 * GdgUploader object.
 * @param options Input options must contain:
 *  - <b>"fileid"</b>: file input ID. It must be created by Cake helper.
 *  - <b>"path"</b>: upload path on server relative to webroot. It will be send as param to upload script
 *  - <b>"app"</b>: application upload URL
 *  - <b>"field"</b>: id of input field to update file name
 */
function GdgUploader(options){
    this.inputId = options['fileid'];
    this.uploadDir = options['path'];
    this.uploadUrl = options['app'];
    this.formInputId = options['field'];
    this.listContainer = null;
    this.queue = [];
    this.uploaded = 0;
    this.uploadedNames = [];
    this.init();
}
GdgUploader.prototype = {
    init: function(){
        var input = document.getElementById(this.inputId);
        input.addEventListener('change', this._onInputChange.bind(this), false);
        input.style.removeProperty('display');
        
        var container = document.createElement('div');
        container.id = 'con_'+this.inputId;
        container.className = 'gdguploader-container';
        input.parentNode.insertBefore(container, input);
        var list = document.createElement('ul');
        list.className = 'gdg-file-list';
        container.appendChild(list);
        this.listContainer = list;
    },
    
    _onInputChange: function(e){
        var files = e.target.files;
        if(files.length == 0) return;
        var size = files.length;
        for(var i=0; i<size; i++){
            this.queue[i] = files[i];
            this._createListElement(files[i], i);
        }
        document.getElementById(this.inputId).style.display = 'none';
        this.upload();
    },
    
    _createListElement: function(file, i){
        var imageType = /image.*/;
        if(!file.type.match(imageType)) {  
            return;
        }  
        var li = document.createElement("li");
        var name = document.createElement("span");
        var preview = document.createElement("span");
        var progress = document.createElement("progress");
        progress.className = 'upl-progress hidden';
        progress.max = file.size;
        progress.value = 0;
        progress.id = 'progress_' + this.inputId + '_' + i;
        preview.className = 'gdg-img-prev';
        name.className = 'gdg-file-name';
        name.innerHTML = file['name'] + '';
        li.appendChild(preview);
        li.appendChild(name);
        li.appendChild(progress);
        
        var img = document.createElement("img");  
        img.classList.add("obj");  
        img.file = file;  
        preview.appendChild(img);  
        
        var reader = new FileReader();  
        reader.onload = (function(aImg) {
            return function(e) {
                aImg.src = e.target.result;
            };        
        })(img);  
        reader.readAsDataURL(file);
        this.listContainer.appendChild(li);
    },

    upload: function(){
        var file = this.queue.shift();
        if(!file){
            this._onUploadFinish();
            return;
        }
        var progress = document.getElementById('progress_' + this.inputId + '_' + this.uploaded);
        progress.style.removeProperty('display');
        var xhr = new XMLHttpRequest();
        var context = this;
        function onUploadError(){
            context.uploaded++;
            progress.style.display = 'none';
            progress.parentNode.classList.add('error');
            window.setTimeout(function(){context.upload();}.bind(context), 50);
        }
        
        
        xhr.upload.addEventListener("progress", function(e) {  
            if (e.lengthComputable) {
                //                var percentage = Math.round((e.loaded * 100) / e.total);  
                progress.value = e.loaded;
            }  
        }.bind(this), false);  
        xhr.addEventListener("load", function(e){
            var responseData = xhr.responseText;
            var data = null;
            try{
                data = JSON.parse(responseData);
            } catch(e){
                console.error("e",responseData,e);
                onUploadError(); 
                return;
            }
            if(data == null){
                onUploadError(); 
                return;
            }
            if(data.error || !data.file){
                console.log(data.error);
                onUploadError(); 
                return;
            }
            this.uploadedNames[this.uploadedNames.length] = data.file;
            this.uploaded++;
            progress.style.display = 'none';
            window.setTimeout(function(){this.upload();}.bind(this), 50);
        }.bind(this), false);
        xhr.upload.addEventListener("error", function(e){  
            onUploadError();
        }.bind(this), false);
        xhr.open('post', this.uploadUrl, true);
        var fd = new FormData();
        fd.append('file', file);
        fd.append('path', this.uploadDir);
        xhr.send(fd);
    },

    _onUploadFinish: function(){
        document.getElementById(this.formInputId).value = this.uploadedNames.join(',');
    }
}

function GdgHelper(){
    if(!window.gdguploadoptions) return;
    if(!window.gdguploadoptions.length || window.gdguploadoptions.length == 0) return;
    this.objects = [];
    var cnt = window.gdguploadoptions.length;
    for(var i=0; i<cnt; i++){
        this.objects[this.objects.length] = new GdgUploader(window.gdguploadoptions[i]);
    }
}


window.gdgupload = new GdgHelper();